# 导入相应模块
import pygame
from pygame.locals import *
import time,random,os

class HeroPlane:
    '''玩家飞机(英雄)'''
    def __init__(self,screen_temp):
        # 玩家飞机的初始位置，玩家飞机图片左上坐标
        self.x = 200
        self.y = 400
        self.screen = screen_temp
        self.image = pygame.image.load(os.path.join(file_path,"me.png"))
        self.bullet_list = [] # 用于玩家的子弹列表
        
    def display(self):
        '''绘制'''
        # 绘制子弹
        for b in self.bullet_list:
            b.display()
            if b.move():
                self.bullet_list.remove(b) #删除炮弹
        # 绘制玩家飞机
        self.screen.blit(self.image,(self.x,self.y))
        
        #########################################################################
    def checkboom(self,enemyplane):
        '''玩家飞机碰撞检测'''
        for enbo in enemyplane.emboomlist:
            if enbo.x+2.5 > self.x + 12 and enbo.x+2.5 < self.x + 92 and enbo.y+10 > self.y + 18 and enbo.y+10 < self.y + 45:
                for i in range(4):
                    Boom(self.screen,self.x,self.y,i).display()
                enemyplane.emboomlist.remove(enbo)
                print("enemy fit")
                return True

    def move_left(self):
        '''左移动飞机'''
        self.x -= 5
        # 防越界
        if self.x <= 0:
            self.x = 0
        
        
    def move_right(self):
        '''右移动飞机'''
        self.x += 5
        if self.x >= 406:
            self.x = 406

    def fire(self):
        '''发射子弹'''
        self.bullet_list.append(Bullet(self.screen,self.x,self.y))

        
class Bullet:
    '''子弹类'''
    def __init__(self,screen_temp,x,y):
        # 玩家飞机的初始位置，玩家飞机图片左上坐标
        self.x = x + 53
        self.y = y
        self.screen = screen_temp
        self.image = pygame.image.load(os.path.join(file_path,"pd.png"))
        
    def display(self):
        '''绘制子弹'''
        self.screen.blit(self.image,(self.x,self.y))
        
    def move(self):
        self.y -= 10
        # 控制子弹内存
        if self.y <= -20:
            return True

class EnemyBullet:
    '''敌机子弹类'''
    def __init__(self,screen_temp,x,y):
        # 玩家飞机的初始位置，玩家飞机图片左上坐标
        self.x = x + 53
        self.y = y + 74
        self.screen = screen_temp
        self.image = pygame.image.load(os.path.join(file_path,"pd3.png"))
        
    def display(self):
        '''绘制子弹'''
        self.screen.blit(self.image,(self.x,self.y))
        
    def move(self):
        self.y += 5
        # 控制子弹内存
        if self.y >= 568:
            return True
        

class EnemyPlane:
    '''敌机类'''
    def __init__(self,screen_temp):
        # 玩家飞机的初始位置，玩家飞机图片左上坐标
        self.x = random.choice(range(408)) # 窗口大小:512*568,512-104=408
        self.y = -75 # 根据敌机图片高:104*74
        self.screen = screen_temp
        self.image = pygame.image.load(os.path.join(file_path,"e"+str(random.choice(range(3)))+".png"))
        self.emboomlist = []
        
    def display(self):
        '''绘制敌机'''
        self.screen.blit(self.image,(self.x,self.y))
        if random.choice(range(30)) == 10:
            self.emboomlist.append(EnemyBullet(self.screen,self.x,self.y)) # 敌机发射子弹
        for b in self.emboomlist:
            b.display()
            if b.move():
                self.emboomlist.remove(b) #删除炮弹
                
 
        
        
    def move(self,hero):
        self.y += 3
        
        if  self.y > 568:
            return True # 判断敌机是否出游戏窗口
        
        # 遍历所有玩家子弹,并执行碰撞检测
        for bo in hero.bullet_list:
            if bo.x > self.x + 12 and bo.x < self.x + 92 and bo.y > self.y + 20 and bo.y < self.y + 60:
                for i in range(4):
                    Boom(self.screen,self.x,self.y,i).display()
                hero.bullet_list.remove(bo)
                return True
        

class Boom:
    '''爆炸效果'''
    def __init__(self,screen_temp,x,y,i_tempt):
        # 传送爆炸坐标
        self.x = x
        self.y = y
        self.screen = screen_temp
        self.image = pygame.image.load(os.path.join(file_path,"bo"+str(i_tempt)+".jpg"))
        
    def display(self):
        '''绘制爆炸效果'''
        self.screen.blit(self.image,(self.x,self.y))

            
def key_control(hero_temp):
    '''键盘控制函数'''
    # 执行退出操作
    for event in pygame.event.get():
        if event.type == QUIT:
            print("exit()")
            exit()
    # 获取按键信息
    pressed_keys = pygame.key.get_pressed()
    # 做判断，并执行对象操作
    if pressed_keys[K_LEFT] or pressed_keys[K_a]:
        print("Left...")
        hero_temp.move_left()
        
    elif pressed_keys[K_RIGHT] or pressed_keys[K_d]:
        print("Right...") #左右键不能同时按下
        hero_temp.move_right()
        
    if pressed_keys[K_SPACE]:
        print("Space...") # 允许左右键 & 空格键同时按下
        hero_temp.fire()


def main():
    '''主程序函数'''
    global file_path

    
    # 设计游戏窗口
    screen = pygame.display.set_mode((512,568),0,0) # （x,y）

    # 创建游戏背景
    background = pygame.image.load(os.path.join(file_path,"bg2.jpg"))
    
    # 创建游戏结束图片
    gameover = pygame.image.load(os.path.join(file_path,"end1.jpg"))
    
    # 创建玩家飞机(英雄)，实例化
    hero = HeroPlane(screen)
    enemyplane = EnemyPlane(screen)
    m = -968
    enemylist = [] # 存放敌机的列表
    while True:
        # 绘制画面
        screen.blit(background,(0,m))
        m +=2
        if m>=-200:
            m = -968
        # 绘制玩家飞机
        hero.display()
        
        # 执行键盘调用
        key_control(hero)
        
        # 随机绘制敌机
        if random.choice(range(50)) == 10:
            enemylist.append(EnemyPlane(screen)) # 随机得出敌机出现概率
            
        # 遍历敌机并移动
        for em in enemylist:
            em.display()
            if em.move(hero):
                enemylist.remove(em) # 如果碰撞敌机,消除敌机
                
            if hero.checkboom(em):
                print("GameOver")
                for i in range(10):
                    pygame.display.update()
                    screen.blit(gameover,(0,150))
                    time.sleep(0.1)
                
                exit()
                # 如果敌机子弹碰撞玩家飞机,消除玩家飞机,GameOver
        
        # 更新显示
        pygame.display.update()

        # 定时显示
        time.sleep(0.04)

# 定义图片路径
file_path = r'D:\python\image'

# 判断当前是否是主运行程序并调用
if __name__ == "__main__":
    main()
